package com.emm.yixun.common.utils;

/*import org.springframework.beans.factory.annotation.Autowired;*/

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

import com.emm.yixun.common.app.base.CommonResDTO;
import com.emm.yixun.common.enums.ResultEnum;
import com.emm.yixun.common.exception.XFUNExceptionCode;
/**
 * 公共类 -  验证用户是否登录或token是否有效
 * @author ny
 *
 */
public class VaildUserToken {

/*	@Autowired*/
	private CacheManager cacheManager;
	
	public CommonResDTO yzUserToken(String merchantId, String userId, String token){
		CommonResDTO resDto = new CommonResDTO();
		//校验当前token是否有效
		Cache  cache = cacheManager.getCache("activeSessionsCache");
		String u_userId = merchantId + userId+"userId";//获取userId缓存key
		String u_token = merchantId + userId+"userId"+"token";//获取token缓存key
		Element element_userId = cache.get(u_userId);
		Element element_token = cache.get(u_token);
		//无缓存或缓存失效
		if(element_userId == null || element_token == null){
			resDto.setResult(ResultEnum.FAILURE.getNo());
			resDto.setErrorCode(XFUNExceptionCode.USER_TOKENERROR.getCode());
			resDto.setErrorMsg(XFUNExceptionCode.USER_TOKENERROR.getDesin());
			return resDto;
		}
		//有缓存未失效，但userId与token错误
		String ele_token = (String) element_token.getValue();
		String ele_user = (String) element_userId.getValue();
		if(!userId.equals(ele_user) && !token.equals(ele_token)){
			resDto.setResult(ResultEnum.FAILURE.getNo());
			resDto.setErrorCode(XFUNExceptionCode.USER_TOKENERROR.getCode());
			resDto.setErrorMsg(XFUNExceptionCode.USER_TOKENERROR.getDesin());
			return resDto;
		}
		resDto.setResult(ResultEnum.SUCCESS.getNo());
		return resDto;
	}
	
}
